<script setup lang="ts">
/**
 * @name RecalculationProgressQuery
 * @description 重算进度查询
 */
import {
  Stopwatch,
  Tickets,
} from '@element-plus/icons-vue'
import type { Action } from 'element-plus'
import type { ComponentExposed } from 'vue-component-type-helpers'
import { DetailModal, SearchForm } from './components'
import {
  defaultFormData,
  defaultPagingParams,
} from './index'
import type {
  CalculationIndicatorRecalculationSelectRecalculationSchedulePageResult as A,
  DictionaryEncoInfo,
  TableColumn,
} from '@/types'
import { calculationIndicatorRecalculationApi } from '@/api'
// ------------------use------------------
// #region
const { form } = useKeepPageStore()
form(['/recalculation-calculation-indicators'])
const { globalProperties, $confirm } = useCurrentInstance()
const { withLoading, loading } = useDefineLoading()
const [tableData, setTableData] = useState<A[]>([])
const [formData, setFormData] = useState<any>({
  ...defaultFormData,
})
const [total, setTotal] = useState<number>(0)
const [timeType, setTimeType] = useState<
  DictionaryEncoInfo[]
>([])
// #endregion
// ------------------静态变量------------------
// #region
const columns: TableColumn<A>[] = [
  {
    key: uuid(),
    type: 'index',
    width: '80',
    label: '序号',
  },
  {
    key: uuid(),
    label: '指标名称',
    prop: 'indicatorName',
  },
  {
    key: uuid(),
    label: '指标编码',
    width: '240',
    prop: 'indicatorNumber',
  },
  {
    key: uuid(),
    label: '时间类型',
    render({ row }) {
      const name = timeType.value.find(
        item => item.dicKey === row.timeType,
      )!.dicValue
      return name
    },
  },
  {
    key: uuid(),
    label: '开始时间',
    render({ row }) {
      return row.dataStartTime ?? '---'
    },
  },
  {
    key: uuid(),
    label: '结束时间',
    render({ row }) {
      return row.dataEndTime ?? '---'
    },
  },
  {
    key: uuid(),
    prop: 'state',
    label: '状态',
    minWidth: 100,
    showOverflowTooltip: false,
  },
  {
    key: uuid(),
    label: '计算指标数量/总数',
    render({ row }) {
      return `${row.completedQuantity}/${row.totalQuantity}`
    },
  },
  {
    key: uuid(),
    label: '失败数量',
    render({ row }) {
      return row.failQuantity ?? '---'
    },
  },
  {
    key: uuid(),
    label: '计算开始时间',
    render({ row }) {
      return row.startTime ?? '---'
    },
  },
  {
    key: uuid(),
    label: '计算结束时间',
    render({ row }) {
      return row.endTime ?? '---'
    },
  },
]
// #endregion
// ------------------动态变量------------------
// #region

// #endregion
// ------------------ref-----------
// #region
const modalRef
  = ref<ComponentExposed<typeof DetailModal>>()
const pagingParams = ref({
  ...defaultPagingParams,
})
// #endregion
// ------------------reactive------
// #region

// #endregion
// ------------------computed------
// #region
// #endregion
// ------------------生命周期------------------
// #region
onBeforeMount(async () => {
  await getTimeType()
  getTableData()
})
// #endregion
// ------------------内置方法---------------------
// #region

// #endregion
// ------------------方法---------------------
// #region
async function stop(id: number) {
  const res: Action = await $confirm(
    '该操作将中止计算，确定中止？',
    '警告',
    {
      type: 'warning',
    },
  ).catch(e => e)

  if (res !== 'confirm')
    return
  await calculationIndicatorRecalculationApi.stopBaseDataJob(
    id,
  )
  globalProperties.$message.success('任务中止成功！')
  getTableData()
}
async function showDetailDialog(row: A) {
  setFormData({ ...defaultFormData, ...row })
  await nextTick()
  modalRef.value?.open()
}
async function getTableData() {
  const { data: res } = await withLoading(
    calculationIndicatorRecalculationApi.selectRecalculationSchedulePage,
  )(pagingParams.value)
  const { total, records } = res
  setTotal(total)
  setTableData(records)
}
async function getTimeType() {
  const { data: res } = await withLoading(
    sysDictionaryEncoApi.queryList,
  )('SHI_JIAN_KE_LI')
  setTimeType(res)
}
// #endregion
</script>

<template>
  <div
    class="padding-sm flex-direction flex align-end container"
  >
    <view-table
      :loading="loading"
      :columns="columns"
      :data="tableData"
      :show-download="false"
    >
      <template #state="{ row }">
        <el-tag v-if="row.state === 0" type="info">
          未开始
        </el-tag>
        <el-tag v-else-if="row.state === 1">
          计算中
        </el-tag>
        <el-tag v-else-if="row.state === 2" type="success">
          计算完成
        </el-tag>
        <el-tag v-else-if="row.state === 3" type="danger">
          部分失败
        </el-tag>
        <el-tag v-else type="danger">
          停止
        </el-tag>
      </template>
      <template #actions>
        <SearchForm
          v-model="pagingParams"
          @search="getTableData"
          @reset="getTableData"
        />
      </template>
      <template #operate="{ row }">
        <TdButton
          title="明细"
          :icon="Tickets"
          type="primary"
          @click="showDetailDialog(row)"
        />
        <TdButton
          title="停止"
          :icon="Stopwatch"
          :disabled="[2, 3, 4].includes(row.state)"
          type="danger"
          @click="stop(row.id)"
        />
      </template>
    </view-table>

    <!-- 分页 -->
    <ListsPagination
      v-model:page-num="pagingParams.pageNumber"
      v-model:page-size="pagingParams.pageSize"
      :total="total"
      @current-change="getTableData"
      @size-change="getTableData"
    />
    <DetailModal ref="modalRef" :data="formData" />
  </div>
</template>

<style lang="scss" scoped>
//------------------组件样式------------------
//-------------样式穿透-------------
</style>
